//
//  CacheAddressBook.m
//  AddressBookDemo
//
//  Created by wulanzhou on 2017/5/11.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

#import "CacheAddressBook.h"
#import "KBAddressBookManager.h"

#define kCacheAddressBookKey @"CacheAddressBook.db"

@interface CacheAddressBook ()
@property (nonatomic,strong) NSString *cachePath;
@end

@implementation CacheAddressBook

+ (instancetype)shareManger{
    static CacheAddressBook *manger = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!manger) {
            manger = [[CacheAddressBook alloc]init];
        }
    });
    return manger;
}

- (NSString *)cachePath {
    if (!_cachePath) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *doc = [paths objectAtIndex:0];
        NSString *fileName = [doc stringByAppendingPathComponent:kCacheAddressBookKey];
        _cachePath = fileName;
        /**
        NSString *filePath = [doc stringByAppendingPathComponent:@"cache"];
        [self createDirectoryWithPath:filePath];
        NSString *fileName = [filePath stringByAppendingPathComponent:kCacheAddressBookKey];
        _cachePath = fileName;
         **/
    }
    return _cachePath;
}

- (void)cacheContacts{

    NSData *data=[NSKeyedArchiver archivedDataWithRootObject:[KBAddressBookManager shareManger].allContacts];
    [data writeToFile:self.cachePath atomically:YES];
    NSLog(@"cachePath = %@",self.cachePath);
}

- (id)getCacheContacts{

    NSData *data = [NSData dataWithContentsOfFile:self.cachePath];
    if (data) {
        
        NSDictionary *allContacts = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        __block NSMutableArray *contacts = [NSMutableArray arrayWithCapacity:0];
        [allContacts enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [contacts addObjectsFromArray:[allContacts objectForKey:key]];
        }];
        
        return contacts;
    }
    return nil;
}

#pragma mark -私有方法
/**
 *  在指定的文件路径中创建文件夹
 *  @param path     文件路径
 *  @return         创建是否成功
 */
- (BOOL)createDirectoryWithPath:(NSString*)path{
    BOOL success=YES;
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if (!(isDir == YES && existed == YES) )
    {
        success=[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return success;
}

@end
